package com.compty.security.manager;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.compty.core.hibernate.HibernateEntityDao;
import com.compty.security.cache.RescCache;
import com.compty.security.domain.Resc;


public class RescManager extends HibernateEntityDao<Resc> {
  
	private RescCache rescCache;
	
    public void setRescCache(RescCache rescCache) {
		this.rescCache = rescCache;
	}
    
	@SuppressWarnings("unchecked")
	public List<Resc> getAllResource(){
    	String hql = "from Resc ";
    	return super.find(hql);
    }

	/**
     * @param o resource.
     */
    @Override
    public void save(Object o) {
        Resc resc = (Resc) o;
        boolean isNew = (resc.getId() == null);
        String orginString = "";

        if (!isNew) {
            Resc orginResc = get(resc.getId());
            orginString = orginResc.getResString();
            getHibernateTemplate().evict(orginResc);
        }

        super.save(o);

        if (!isNew
                && !StringUtils.equals(resc.getResString(), orginString)) {
            removeRescInCache(orginString);
        }

        saveRescInCache(resc);
    }

    /**
     * @param o resource.
     */
    @Override
    public void remove(Object o) {
        super.remove(o);

        Resc resc = (Resc) o;
        removeRescInCache(resc.getResString());
    }

    /**
     * 把资源保存里缓存.
     *
     * @param resc 资源
     */
    private void saveRescInCache(Resc resc) {
        rescCache.put(resc.getResString(), resc);
    }

    /**
     * 从缓存里删除资源.
     *
     * @param resString 资源内容
     */
    public void removeRescInCache(String resString) {
    	 rescCache.remove(resString);
    }
    
    public Resc getResourceFromCache(String resString){
    	if(rescCache.get(resString) != null){
    		Resc  resc = (Resc) rescCache.get(resString);
        	return resc;
    	}
    	return null;
    }
}
